<?php

namespace app\im\service;

use app\im\model\FriendsModel;
use app\im\model\UserModel;
use Exception;

class UserService
{
    protected $db;

    public function __construct()
    {
        $this->db = new UserModel();
    }

    /**
     * 个人资料
     */
    public function profile($userId)
    {
        return $this->db->find($userId);
    }

    /**
     * 我的好友
     *
     * @param int $userId   用户ID
     */
    public function friends($userId)
    {
        return FriendsModel::alias('f')
            ->join('users u', 'f.target_user_id = u.id')
            ->where('f.user_id', $userId)
            ->fieldRaw('u.nickname,u.avatar,u.sex,u.account')
            ->order('f.id desc')
            ->select();
    }

    /**
     * 注册
     *
     * @param 账号 $account
     * @param 密码 $password
     */
    public function register($account, $password)
    {
        $user = $this->db->getByAccount($account);
        if ($user) {
            return false;
        }
        $salt = bin2hex(random_bytes(8));
        $res = $this->db->insert([
            'account' => $account,
            'create_time' => time(),
            'salt' => $salt,
            'password' => password_encrypt($password, $salt),
        ]);
        return $res;
    }

    /**
     * 登陆
     *
     * @param string $account   账号
     * @param string $password  密码
     */
    public function login($account, $password)
    {
        $user = $this->db->getByAccount($account);
        if (!$user) {
            throw new Exception('账号不存在');
        }
        if (!$this->checkPassword($user, $password)) {
            throw new Exception('密码不对');
        }

        $token = generate_token();
        cache($token, serialize($user));
        $user['token'] = $token;

        unset($user['slat'], $user['password']);

        return $user;
    }

    /**
     * 检测密码是否匹配
     *
     * @param array $user       用户数组  
     * @param string $password  明文密码
     */
    protected function checkPassword($user, $password)
    {
        return $user['password'] == password_encrypt($password, $user['salt']);
    }
}
